package com.gph.saviorframework.security.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.gph.saviorframework.Constants;
import com.gph.saviorframework.oa.service.sysconfig.SYSConfigService;
import com.gph.saviorframework.security.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录控制器
 *
 * @author guopeihui
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private SYSConfigService sysConfigService;

    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    @ResponseBody
    public String login(
            @RequestParam(value = "loginType",required = false) String loginType,
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Map backValue=new HashMap();
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            token.setRememberMe(true);

            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("_CURRENT_USER_", userService.get(username));
            session.setAttribute("_USERNAME_", username);

            backValue.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        }
        catch (Exception ex) {
            ex.printStackTrace();
            backValue.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            backValue.put(Constants.DEFAULT_ERROR_KEY, ex.getLocalizedMessage());
        }
        return JSONArray.toJSONString(backValue);
    }

    @RequestMapping(value = "/dologout", method = RequestMethod.GET)
    public void logout() {
        try {
            SecurityUtils.getSubject().logout();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @RequestMapping(value = "/login")
    public String showLoginForm(HttpServletRequest req, Model model) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:admin";
        }

        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        String error = null;
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if("Verification Error".equals(exceptionClassName)) {
            error = "验证码错误";
        }else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName))
            error = " 账号审核中,请等候。";
        else if(exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }
        model.addAttribute("error", error);
        /*model.addAttribute("appTitle",sysConfigService.get("appTitle").getValue());
        model.addAttribute("hotline",sysConfigService.get("hotline").getValue());
        model.addAttribute("copyright",sysConfigService.get("copyright").getValue());
        model.addAttribute("ICP",sysConfigService.get("ICP").getValue());*/
        return "login2_create";
    }
}
